package m2;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Consumer {
    public static void main(String[] args) throws IOException, TimeoutException {
        //连接
        ConnectionFactory f = new ConnectionFactory();
        f.setHost("192.168.64.140");
        f.setUsername("admin");
        f.setPassword("admin");
        Channel c = f.newConnection().createChannel();

        //定义队列
        c.queueDeclare("task_queue", true, false, false, null);

        //回调对象
        DeliverCallback deliverCallback = new DeliverCallback() {
            @Override
            public void handle(String consumerTag, Delivery message) throws IOException {
                String msg = new String(message.getBody());
                System.out.println("收到:"+msg);
                //遍历消息字符串的所有字符,每个点字符都暂停1s,模拟耗时消息
                for (int i=0;i<msg.length();i++){
                    if (msg.charAt(i) == '.'){
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
                //手动发送回执
                //参数:   1.回执数据      2.是否同时确认多条消息
                c.basicAck(message.getEnvelope().getDeliveryTag(),false);
                System.out.println("----------消息处理结束\n\n");

            }
        };
        CancelCallback cancelCallback = new CancelCallback() {
            @Override
            public void handle(String consumerTag) throws IOException {
            }
        };

        //每次只抓取一条消息,这条消息处理完之前,不抓取下一条
        c.basicQos(1);

        //消费数据
        //第二个参数 ack模式  true-自动确认  false-手动确认
        /*
        参数：
             1.队列名字
             2.ack模式，true-自动ack，false-手动ack
             3.处理消息的回调对象
             4.取消消息处理的回调对象
         */
        c.basicConsume("task_queue", false, deliverCallback, cancelCallback);
    }

}
